package com.jywl.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;  
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jywl.entity.Column;  
public class FileUtil {
	public static void  creatFile(String path) {  
	    File file = new File(path);  
	    File dir = file.getParentFile();  
	    if (!dir.exists()) {  
	        dir.mkdirs();  
	    }  
	    try {  
	        file.createNewFile();  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    }  
	}
	/** 
     * 创建ZIP文件 
     * @param sourcePath 文件或文件夹路径 
     * @param zipPath 生成的zip文件存在路径（包括文件名） 
     */  
    public static void createZip(String sourcePath, String zipPath) {  
        FileOutputStream fos = null;  
        ZipOutputStream zos = null;  
        try {  
            fos = new FileOutputStream(zipPath);  
            zos = new ZipOutputStream(fos);  
          
            //createXmlFile(sourcePath,"293.xml");  
            writeZip(new File(sourcePath), "", zos);  
        } catch (FileNotFoundException e) {  
         
        } finally {  
            try {  
                if (zos != null) {  
                    zos.close();  
                }  
            } catch (IOException e) {  
               
            }  
  
        }  
    }  
  
    private static void writeZip(File file, String parentPath, ZipOutputStream zos) {  
        if(file.exists()){  
            if(file.isDirectory()){//处理文件夹  
                parentPath+=file.getName()+File.separator;  
                File [] files=file.listFiles();  
                if(files.length != 0)  
                {  
                    for(File f:files){  
                        writeZip(f, parentPath, zos);  
                    }  
                }  
                else  
                {       //空目录则创建当前目录  
                        try {  
                            zos.putNextEntry(new ZipEntry(parentPath));  
                        } catch (IOException e) {  
                            // TODO Auto-generated catch block  
                            e.printStackTrace();  
                        }  
                }  
            }else{  
                FileInputStream fis=null;  
                try {  
                    fis=new FileInputStream(file);  
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());  
                    zos.putNextEntry(ze);  
                    byte [] content=new byte[1024];  
                    int len;  
                    while((len=fis.read(content))!=-1){  
                        zos.write(content,0,len);  
                        zos.flush();  
                    }  
  
                } catch (FileNotFoundException e) {  
                } catch (IOException e) {  
                }finally{  
                    try {  
                        if(fis!=null){  
                            fis.close();  
                        }  
                    }catch(IOException e){  
                    }  
                }  
            }  
        }  
    } 
    public static String txt2String(String file){
        StringBuilder result = new StringBuilder();
        try{
        	InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");  
        	BufferedReader br = new BufferedReader(isr);  
           // BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result.append(s+System.lineSeparator());
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
    public static boolean writeTxtFile(String content,String  fileName){  
    	  boolean flag=false;  
    	  FileOutputStream o=null;  
    	  try {  
    	   o = new FileOutputStream(fileName);  
    	      o.write(content.getBytes("utf-8"));  
    	      o.close();  
    	   flag=true;  
    	  } catch (Exception e) {  
    	   // TODO: handle exception  
    	   e.printStackTrace();  
    	  }finally{  
    	  }  
    	  return flag;  
    	 }  
	
	public static String getTempFolder() {
		return System.getProperty("java.io.tmpdir");
	}
	 /** 
     * 上传到临时目录
     *  
     * @author sunxq 
     * @date 2017年8月24日
     * @param request 
     * @throws Exception 
     */  
    public static String upload(HttpServletRequest request
           ) throws Exception { 
    	String path="";
          if(ServletFileUpload.isMultipartContent(request)) {       	
             MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
              Iterator<?> iter=multiRequest.getFileNames();
              while(iter.hasNext())
              {
                  MultipartFile file=multiRequest.getFile(iter.next().toString());
                  if(file!=null)
                  {
                  	String    dir = getTempFolder();
        			 File dirname = new File(dir); 
        				if (!dirname.isDirectory()) { //目录不存在 
        					dirname.mkdirs(); //创建目录
        				} 	
        			 path =dirname.getAbsolutePath()+File.separator+CommUtil.UUid()+file.getOriginalFilename();
                     file.transferTo(new File(path));
                  }
              }
             
          }
          return path; 
    }
	public static void createExcelFile(String excelFile, List<Column> columns) {
		File file = new File(excelFile);  
	    File dir = file.getParentFile();  
	    if (!dir.exists()) {  
	        dir.mkdirs();  
	    }  
		Workbook wb = null;
	    FileOutputStream out = null;
	    try {	
			wb = new XSSFWorkbook();
			out = new FileOutputStream(excelFile);
			Sheet sheet = wb.createSheet("填写数据");
			Row r1 = sheet.createRow(0);
			Row r2 = sheet.createRow(1);
			int i =0;
			for (Column c : columns) {
				if(("Y".equals(c.getIspersistence())||"Y".equals(c.getIsshow()))&&null==c.getIspk()){
					Cell cell1 =r1.createCell(i);
					Cell cell2 =r2.createCell(i);
					cell1.setCellValue(c.getPropertyname());
					cell2.setCellValue(null==c.getComments()?c.getPropertyname():c.getComments());
					i++;
				}
			}
		    wb.write(out);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
	        if (wb != null) {
	           try {wb.close();} catch (Exception e2) {e2.printStackTrace();} 
	        }
	        }if (out != null) {
	        	try {out.close();} catch (Exception e2) {e2.printStackTrace();
	        } 
	        	
	    }
	 }
	public static void main(String[] args) {
		String path = "c:\\aaa\\bbb\\ccc\\ycy.xlsx";
		createExcelFile(path,null);
	}
}


